package fi.libros.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.support.SessionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;

import fi.libros.domain.Book;
import fi.libros.gae.MappingDatastoreService;


@Controller
@Service
@Repository
@RequestMapping("/bookAdd.do")
public class BookAddForm {
	final Logger logger = LoggerFactory.getLogger(BookAddForm.class);
	
	@Autowired
	private MappingDatastoreService datastore;


    @InitBinder
    public void initBinder(WebDataBinder dataBinder) {
    	dataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(false)); 
    }
	
	@RequestMapping(method = RequestMethod.GET)
	public String setupForm(Model model) {
		logger.debug("setupForm: "+model);
		Book book = new Book();
		model.addAttribute("book", book);
		return "bookCreate";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute("book") Book book, BindingResult result, SessionStatus status)
	throws EntityNotFoundException {
		Key k = datastore.put(book);
		k = datastore.put(book);
		logger.debug("* created book with id: "+k.getId());
		Book b2 = datastore.get(k, Book.class);
		logger.debug("processSubmit"+book+", "+result+", "+status);
		logger.debug("entity: "+b2);
		return "main";
	}

	public void setDatastore(MappingDatastoreService datastore) {
		this.datastore = datastore;
	}
	
}
